<?php


namespace Drupal\shusy_product_category\ViewsController\handler\field;


use views_handler_field_prerender_list;

class ShusyProductCategoryCategoriesViewsField extends views_handler_field_prerender_list {

  public function construct() {
    parent::construct();
    $this->additional_fields['category_id'] = [
      'table' => 'shusy_product',
      'field' => 'id',
    ];
  }

  public function query() {
    $this->add_additional_fields();
    $this->field_alias = $this->aliases['category_id'];
  }

  public function pre_render(&$values) {
    $pids = [];
    $this->items = [];
    foreach ($values as $result) {
      $pids[] = $this->get_value($result, NULL, TRUE);
    }
    if ($pids) {
      $result = db_query("SELECT b.product_id, b.category_id, t.name FROM {shusy_category} t
INNER JOIN {shusy_product_category} b 
ON b.category_id = t.id 
WHERE b.status=1 AND b.product_id IN (:pids) ORDER BY t.name",
        [':pids' => $pids]);
      foreach ($result as $item) {
        $this->items[$item->product_id][$item->category_id]['name'] = check_plain($item->name);
        $this->items[$item->product_id][$item->category_id]['category_id'] = $item->category_id;
      }
    }
  }

  public function render_item($count, $item) {
    return $item['name'];
  }
}
